//https://leetcode.cn/problems/surrounded-regions/

class Solution {
    int dx[4] = { 0,0,-1,1 };
    int dy[4] = { -1,1,0,0 };
    int m, n;
    bool vit[201][201];
public:
    void solve(vector<vector<char>>& board) {
        m = board.size(), n = board[0].size();

        //处理边界上的‘o’
        for (int j = 0; j < n; j++)
        {
            if (board[0][j] == 'O' && !vit[0][j]) bfs(board, 0, j);
            if (board[m - 1][j] == 'O' && !vit[m - 1][j]) bfs(board, m - 1, j);
        }

        for (int i = 0; i < m; i++)
        {
            if (board[i][0] == 'O' && !vit[i][0]) bfs(board, i, 0);
            if (board[i][n - 1] == 'O' && !vit[i][n - 1]) bfs(board, i, n - 1);
        }

        //复原
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == 'O')
                    board[i][j] = 'X';
                if (board[i][j] == '.')
                    board[i][j] = 'O';
            }
        }

    }

    void bfs(vector<vector<char>>& board, int i, int j)
    {
        queue<pair<int, int>> q;
        q.push({ i,j });
        vit[i][j] = true;
        board[i][j] = '.';

        while (q.size())
        {
            auto [a, b] = q.front();
            q.pop();

            for (int k = 0; k < 4; k++)
            {
                int x = a + dx[k];
                int y = b + dy[k];

                if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O' && !vit[x][y])
                {
                    q.push({ x,y });
                    vit[x][y] = true;
                    board[x][y] = '.';
                }
            }
        }
    }
};